

let obj = {
    name: 'csc',
    arr:[1, 2, 3],
    obj1: {

    }
}

// JSON.parse(JSON.stringify())

let obj1 = JSON.parse(JSON.stringify(obj))
obj.name = '123'
console.log(obj1.name, obj.name);

// 这种方法有缺点

// 递归
// 注意循环引用

let isObject = (obj) => {
    return obj instanceof Object
}

function deepClone(obj1, map = new WeakMap()) {
    if(!isObject(obj1)) {
        return obj1
    }
    if(map.get(obj1)) {
        return map.get(obj1)
    }
    let target = obj1.constructor()
    map.set(obj1, target)

    for(let key in obj1) {
        if(obj1.hasOwnProperty(key)) {
            target[key] = isObject(obj1[key]) ? deepClone(obj1[key]) : obj1[key]
        }
    }
    return target
}

obj.arr = obj.obj1
obj.obj1 = obj.arr

let obj2 = deepClone(obj)
obj.arr[0] = 8
console.log(obj2)